package com.lean.android.ad.workflow

import android.app.Activity
import androidx.annotation.RestrictTo
import com.lean.android.ad.core.AdLoaders
import com.lean.android.ad.core.ErrorCode
import com.lean.android.ad.core.VipDialogBlockChain
import com.lean.android.ad.repository.localcache.AdLocalCache
import com.lean.android.ad.utils.AdLog


@RestrictTo(RestrictTo.Scope.LIBRARY)
class VipDialogNode(
    private val activity: Activity, private val callback: WorkFlows.MainFlowCallback
) : WorkFlowNode {
    override fun enterCondition(): Boolean {
        return !AdLocalCache.vipDialogShowed && !(activity.isFinishing || activity.isDestroyed)
    }

    override fun enter(workFlow: WorkFlow) {
        if (activity.isFinishing || activity.isDestroyed) {
            AdLog.d(AdLog.AdWorkFlowTag, "VipDialogNode enter, but activity is destroyed, skip.")
            exit(workFlow)
        } else {
            val chain = object : VipDialogBlockChain {
                override fun onAccept(afterCall: (code: Int) -> Unit, exitFlow: Boolean) {
                    val rewardCall = fun(errorCode: Int) {
                        afterCall(errorCode)
                        if (errorCode == ErrorCode.Success) {
                            AdLocalCache.vipDialogShowed = true
                            exit(workFlow)
                        } else if (exitFlow) {
                            exit(workFlow)
                        }
                    }
                    AdLoaders.startRewardAd(activity, onReward = {
                        rewardCall(ErrorCode.Success)
                    }, onInvalid = { errorCode ->
                        rewardCall(errorCode)
                    })
                }

                override fun deniedWithAd(onReward: (code: Int) -> Unit, exitFlow: Boolean) {
                    AdLoaders.startRewardAd(activity, onReward = {
                        onReward(ErrorCode.Success)
                        exit(workFlow)
                    }, onInvalid = { errorCode ->
                        onReward(errorCode)
                        if (errorCode == ErrorCode.Success) {
                            exit(workFlow)
                        } else if (exitFlow) {
                            exit(workFlow)
                        }
                    })
                }

                override fun onDenied() {
                    exit(workFlow)
                }
            }
            callback.showVipDialog(chain)
            AdLog.d(AdLog.AdWorkFlowTag, "VipDialogNode enter, show vip dialog.")
        }

    }

}